package com.cheer.job;

import cn.hutool.core.date.DateUtil;
import com.cheer.entity.User;
import com.cheer.enums.RoleEnum;
import com.cheer.service.UserService;
import com.google.common.base.Objects;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账号锁定任务
 * <p>
 * Created by lx on 2022/11/11.
 */
@Component
public class AccountLockedTask {

    private final static Logger LOGGER = LoggerFactory.getLogger(AccountLockedTask.class);

    @Autowired
    private UserService userService;

    @Scheduled(cron = "0 0 0 * * *")
    public void accountLocked() {

        try {

            List<User> list = userService.list();
            if (CollectionUtils.isEmpty(list)) return;

            list = list.stream()
                    .filter(user -> !user.getLocked() && user.getLockedTime() != null
                            && Objects.equal(user.getRole(), RoleEnum.USER.getCode())
                            && user.getLockedTime().getTime() <= DateUtil.offsetDay(new Date(), -1).getTime())
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(list)) return;

            // 销户
            list.forEach(user -> {
                User updateUser = new User().setId(user.getId()).setLocked(true);
                userService.updateById(updateUser);
            });

        } catch (Exception e) {
            LOGGER.error("销户失败", e);
        }

    }
}
